package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.server.pojo.UserSoul;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(version = "1.0.0")
public class TestSoulApiImpl implements TestSoulApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveTestResult(UserSoul userSoul) {
        if (null==userSoul){
            return null;
        }

        try {
            Query query=Query.query(Criteria.where("userId").is(userSoul.getUserId()));
            UserSoul one = this.mongoTemplate.findOne(query, UserSoul.class);


            if (null==one){
                userSoul.setQuestionTableOne(0);
                return this.mongoTemplate.save(userSoul).getId().toHexString();

            }else {
                Update update=Update.update("typeId",userSoul.getTypeId())
                        .set("questionTableTwo",one.getQuestionTableOne()==0?0:1)
                        .set("questionTableThree",one.getQuestionTableTwo()==0?0:1)
                        .set("questionTableAll",one.getQuestionTableThree()==0?0:1)
                        .set("waiXiang",userSoul.getWaiXiang())
                        .set("chouXiang",userSoul.getChouXiang())
                        .set("liXing",userSoul.getLiXing())
                        .set("panDuan",userSoul.getPanDuan());
                UpdateResult updateResult = this.mongoTemplate.updateFirst(query, update, UserSoul.class);
                return  one.getId().toHexString();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public UserSoul findById(Long userId) {
        Query query1=Query.query(Criteria.where("userId").is(userId));
        UserSoul userSoul = mongoTemplate.findOne(query1, UserSoul.class);
        return userSoul;
    }

    /**
     * 更据用户id查询用户灵魂表
     *
     * @param id 用户id
     * @return
     */
    @Override
    public UserSoul queryUserSoulById(String id) {
        return mongoTemplate.findById(new ObjectId(id), UserSoul.class);
    }


    /**
     * 根据用户性格id查询性格相同的人
     *
     * @param typeId 性格id
     * @return
     */
    @Override
    public List<UserSoul> queryUserSoulList(Integer typeId) {
        Query query = Query.query(Criteria.where("typeId").is(typeId));

        return mongoTemplate.find(query, UserSoul.class);

    }
}
